﻿using System;
using System.Globalization;
using System.Threading;
using System.Web.Mvc;

using mvcForum.Core;
using mvcForum.Core.Abstractions.Interfaces;
using mvcForum.Core.Specifications;
using mvcForum.Web.Events;
using mvcForum.Web.Filters;
using mvcForum.Web.Areas.Forum.Controllers;
using mvcForum.Web.Interfaces;
using mvcForum.Core.Interfaces.Data;

namespace mvcForum.Web.Controllers {

	public abstract class ForumBaseController : BaseController {
		private readonly IRepository<ForumUser> userRepository;
		protected readonly IContext context;
		private ForumUser user = null;

		#region Constructors
		protected ForumBaseController()
			: this(null, null) {
		}

		protected ForumBaseController(IWebUserProvider userProvider, IContext context)
			: base(userProvider) {

			this.context = (context == null ? DependencyResolver.Current.GetService<IContext>() : context);
			this.userRepository = this.context.GetRepository<ForumUser>();
		}
		#endregion

		protected override void OnAuthorization(AuthorizationContext filterContext) {
			base.OnAuthorization(filterContext);

			// Is this a authenticated request?
			if (filterContext.RequestContext.HttpContext.User.Identity.IsAuthenticated) {
				// Oh yeah! Get the user!
				if (this.userProvider.Authenticated) {
					ForumUser user = this.userProvider.ActiveUser;
					// Did we get one? Is it an external account? And we're not already on the profile update page? And the e-mail address is one we constructed?
					if (user != null && user.ExternalAccount && filterContext.Controller.GetType() != typeof(mvcForum.Web.Areas.Forum.Controllers.ProfileController) && user.EmailAddress.EndsWith("repl@ce.this")) {
						// Let's force the user to type in an e-mail address!
					}
				}
			}
		}

		/// <summary>
		/// The authenticated user, if any.
		/// </summary>
		protected new ForumUser ActiveUser {
			get {
				return this.userProvider.ActiveUser;
			}
		}

		protected IContext Context { get { return this.context; } }
		protected IRepository<ForumUser> ForumUserRepository { get { return this.userRepository; } }
		protected IRepository<TEntity> GetRepository<TEntity>() where TEntity : class {
			return this.Context.GetRepository<TEntity>();
		}
	}
}